from flask import Flask, render_template, request, jsonify,Response, redirect, url_for, session
from werkzeug.utils import secure_filename  # 确保添加这行导入语句
import sqlite3
import os
import re
from zipfile import ZipFile

app = Flask(__name__)

# 设置密钥，用于加密会话数据，在实际应用中应设置为更复杂安全的字符串
app.config['SECRET_KEY'] = 'your_secret_key'

# 数据库连接配置（这里是SQLite示例）
DB_PATH = 'users.db'
# 设置请求体大小限制为16MB（可根据实际需求调整大小）
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
app.config['JSON_AS_ASCII'] = False  # 允许JSON数据中包含非ASCII字符（根据实际需求设置，这里主要是确保配置完整性）
app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True  # 格式化返回的JSON数据，方便查看，非必需

# 假设之前创建比赛文件夹的根目录，需根据实际情况调整路径
COMPETITION_FILES_ROOT = 'competition_files'

def create_user_table():
    with sqlite3.connect(DB_PATH) as conn:
        cursor = conn.cursor()
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS users (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                username TEXT NOT NULL,
                password TEXT NOT NULL,
                is_admin INTEGER NOT NULL DEFAULT 0
            )
        ''')


def init_super_admin():
    with sqlite3.connect(DB_PATH) as conn:
        cursor = conn.cursor()
        super_admin_username = "admin"
        # 先查询是否已经存在超级管理员账号
        cursor.execute('SELECT * FROM users WHERE username =? AND is_admin = 1', (super_admin_username,))
        existing_admin = cursor.fetchone()
        if not existing_admin:
            data = {
                "username": "admin",
                "password": "admin123",
                "is_admin": 1
            }
            columns = ', '.join(data.keys())
            placeholders = ', '.join(['?'] * len(data))
            query = f"INSERT INTO users ({columns}) VALUES ({placeholders})"
            cursor.execute(query, tuple(data.values()))


@app.route('/')
def index():
    return render_template('index.html')


@app.route('/login', methods=['POST'])
def login():
    username = request.form['username']
    password = request.form['password']

    with sqlite3.connect(DB_PATH) as conn:
        cursor = conn.cursor()
        cursor.execute('SELECT * FROM users WHERE username =? AND password =?', (username, password))
        user = cursor.fetchone()

    if user:
        # 设置登录状态到session中
        session['logged_in'] = True
        session['is_admin'] = user[3] == 1
        session['username'] = username
        return jsonify({"success": True, "is_admin": session['is_admin'], "message": "登录成功"})
    else:
        return jsonify({"success": False, "message": "用户名或密码错误，请重新登录"})


@app.route('/admin_panel')
def admin_panel():
    print("进入 /admin_panel 路由检查")
    print(f"当前 session 中的 logged_in 值: {session.get('logged_in', None)}")
    print(f"当前 session 中的 is_admin 值: {session.get('is_admin', None)}")
    if 'logged_in' in session and session['is_admin']:
        print("满足登录且为管理员权限，准备渲染 admin_panel.html 模板")
        try:
            return render_template('admin_panel.html', username=session['username'])
        except Exception as e:
            print(f"渲染 admin_panel 页面出现错误: {e}")
            return redirect(url_for('index'))
    else:
        print("未满足登录或不是管理员权限，重定向到首页")
        return redirect(url_for('index'))


@app.route('/user_panel')
def user_panel():
    if 'logged_in' in session and not session['is_admin']:
        print("用户名：", session['username'])
        return render_template('user_panel.html', username=session['username'])
    else:
        return redirect(url_for('index'))


# 新增退出登录路由
@app.route('/logout', methods=['POST'])
def logout():
    print("logout")
    try:
        # 清除会话中的用户相关信息，比如登录状态标识等
        session.pop('logged_in', None)
        session.pop('user_id', None)
        session.pop('is_admin', None)
        return jsonify({"success": True, "message": "退出登录成功"})
    except Exception as e:
        print(f"退出登录出现错误: {e}")
        return jsonify({"success": False, "message": "退出登录出现错误，请稍后再试"})


# 新增单独创建用户路由，修改此处逻辑以配合前端弹窗提醒需求（返回状态码和消息，前端根据此来处理弹窗展示）
@app.route('/create_user', methods=['POST'])
def create_user():
    if 'logged_in' in session and session['is_admin']:
        new_username = request.form['new_username']
        new_password = request.form['new_password']

        with sqlite3.connect(DB_PATH) as conn:
            cursor = conn.cursor()
            # 检查用户名是否已存在的查询
            cursor.execute('SELECT * FROM users WHERE username =?', (new_username,))
            existing_user = cursor.fetchone()

            if existing_user:
                print(f"创建用户失败，用户名 {new_username} 已存在")
                return jsonify({"success": False, "message": "用户名重复，创建失败"}), 400  # 返回 400 状态码表示请求错误
            try:
                cursor.execute('INSERT INTO users (username, password) VALUES (?,?)', (new_username, new_password))
                print(f"成功创建用户 {new_username}")
            except sqlite3.Error as e:
                print(f"创建用户时数据库插入操作出现错误: {e}")
                return jsonify({"success": False, "message": "创建用户出现数据库错误，请稍后再试"}), 500  # 返回 500 状态码表示服务器内部错误
            return jsonify({"success": True, "message": "用户创建成功"}), 200  # 返回 200 状态码表示成功

    else:
        print("未满足登录或管理员权限要求，无法创建用户")
        return jsonify({"success": False, "message": "请先登录或权限不足"}), 401  # 返回 401 状态码表示未授权


# 新增删除用户路由
@app.route('/delete_user', methods=['POST'])
def delete_user():
    if 'logged_in' in session and session['is_admin']:
        user_id_to_delete = request.form['user_id']

        with sqlite3.connect(DB_PATH) as conn:
            cursor = conn.cursor()
            try:
                cursor.execute('DELETE FROM users WHERE id =?', (user_id_to_delete,))
                conn.commit()  # 提交事务，确保数据库更改生效
                print(f"成功删除用户，用户ID为 {user_id_to_delete}")
                return jsonify({"success": True, "message": "用户删除成功"})
            except sqlite3.Error as e:
                print(f"数据库删除操作出现错误: {e}")
                return jsonify({"success": False, "message": "用户删除出现数据库错误，请稍后再试"})
    else:
        print("未满足登录或管理员权限要求，无法删除用户")
        return jsonify({"success": False, "message": "请先登录或权限不足"})


# 新增密码重置路由
@app.route('/reset_password', methods=['POST'])
def reset_password():
    if 'logged_in' in session and session['is_admin']:
        user_id = request.form['user_id']

        with sqlite3.connect(DB_PATH) as conn:
            cursor = conn.cursor()
            try:
                cursor.execute('UPDATE users SET password =? WHERE id =?', ('12345', user_id))
                print(f"成功重置用户 {user_id} 的密码为12345")
            except sqlite3.Error as e:
                print(f"重置密码时数据库操作出现错误: {e}")
                return jsonify({"success": False, "message": "重置密码出现数据库错误，请稍后再试"})

        return jsonify({"success": True, "message": "用户密码已成功重置为12345"})
    else:
        print("未满足登录或管理员权限要求，无法重置密码")
        return jsonify({"success": False, "message": "请先登录或权限不足"})


# 新增获取用户列表路由
@app.route('/get_user_list', methods=['GET'])
def get_user_list():
    if 'logged_in' in session and session['is_admin']:
        with sqlite3.connect(DB_PATH) as conn:
            cursor = conn.cursor()
            cursor.execute('SELECT * FROM users')  # 获取所有用户信息（你也可以根据需求调整查询条件）
            users = cursor.fetchall()
            userList = []
            for user in users:
                userList.append({
                    "id": user[0],
                    "username": user[1],
                    "password": user[2],  # 这里把密码也添加进去，方便前端可能的展示需求，实际应用中可按需调整安全性
                    "is_admin": user[3] == 1
                })
            print(f"获取到用户列表，共 {len(userList)} 个用户信息")
            return jsonify({"success": True, "userList": userList})
    else:
        print("未满足登录或管理员权限要求，无法获取用户列表")
        return jsonify({"success": False, "message": "请先登录或权限不足"})


# 新增批量创建用户路由，按照新规则创建用户
@app.route('/batch_create_users', methods=['POST'])
def batch_create_users():
    if 'logged_in' in session and session['is_admin']:
        prefix = request.form.get('prefix')
        start_num = int(request.form.get('start_num'))
        end_num = int(request.form.get('end_num'))

        with sqlite3.connect(DB_PATH) as conn:
            cursor = conn.cursor()
            created_count = 0
            for num in range(start_num, end_num + 1):
                username = f"{prefix}{num}"
                cursor.execute('SELECT * FROM users WHERE username =?', (username,))
                existing_user = cursor.fetchone()
                if not existing_user:
                    try:
                        cursor.execute('INSERT INTO users (username, password) VALUES (?,?)', (username, "12345"))
                        created_count += 1
                        print(f"成功批量创建用户，已创建 {created_count} 个用户，当前创建的用户名为 {username}")
                    except sqlite3.Error as e:
                        print(f"批量创建用户时插入数据出现错误: {e}")
            return jsonify({"success": True, "message": f"成功创建 {created_count} 个用户"})
    else:
        print("未满足登录或管理员权限要求，无法批量创建用户")
        return jsonify({"success": False, "message": "请先登录或权限不足"})


# 新增批量重置密码路由
@app.route('/batch_reset_password', methods=['POST'])
def batch_reset_password():
    if 'logged_in' in session and session['is_admin']:
        #print("修改密码的 post: ", request.form)
        user_ids = request.form.get('user_ids[]')
       # print("修改密码：用户：", user_ids)
        if (len(user_ids) == 0):
            return jsonify({"success": False, "message": "用户传参错误"})
        with sqlite3.connect(DB_PATH) as conn:
            cursor = conn.cursor()
            for user_id in user_ids:
                try:
                    cursor.execute('UPDATE users SET password =? WHERE id =?', ('12345', user_id))
                    print(f"成功批量重置用户 {user_id} 的密码为12345")
                except sqlite3.Error as e:
                    print(f"批量重置密码时数据库操作出现错误: {e}")
            return jsonify({"success": True, "message": "所选用户密码已成功批量重置为12345"})
    else:
        print("未满足登录或管理员权限要求，无法批量重置密码")
        return jsonify({"success": False, "message": "请先登录或权限不足"})


# 新增批量删除用户路由，优化异常处理并返回详细错误信息，同时保留调试程序部分
@app.route('/batch_delete_users', methods=['POST'])
def batch_delete_users():
    if 'logged_in' in session and session['is_admin']:
        # 先检查请求头中的Content-Type，判断前端发送的数据格式
        content_type = request.headers.get('Content-Type')
        print(f"接收到的请求Content-Type: {content_type}")
        if content_type == 'application/json':
            try:
                post_json_data = request.get_json()
                print("接收到的POST JSON信息:", post_json_data)
                # 假设前端JSON数据中用户ID列表的键是'user_ids'，根据实际情况调整
                user_ids = post_json_data.get('user_ids', [])
            except Exception as e:
                print(f"获取POST JSON数据出现错误: {e}")
                user_ids = []
        elif content_type and 'application/x-www-form-urlencoded' in content_type:
            user_ids = request.form.getlist('user_ids')
        else:
            print("不支持的请求数据格式")
            return jsonify({"success": False, "message": "不支持的请求数据格式，请检查后重新发送"})

        error_messages = []  # 用于收集每个删除操作出现的错误信息
        success_count = 0  # 用于记录成功删除的用户数量
        with sqlite3.connect(DB_PATH) as conn:
            cursor = conn.cursor()
            for user_id in user_ids:
                print("check ID", user_id)
                try:
                    cursor.execute('DELETE FROM users WHERE id =?', (user_id,))
                    conn.commit()  # 提交单个删除事务，确保数据库更改生效
                    success_count += 1
                    print("suc")
                except sqlite3.Error as e:
                    error_detail = f"删除用户（ID：{user_id}）时数据库操作出现错误: {e.args[0]}"
                    print(error_detail)
                    error_messages.append(error_detail)
            if error_messages:
                return jsonify({
                    "success": False,
                    "message": "部分用户删除失败，以下是详细错误信息：" + "; ".join(error_messages),
                    "error_list": error_messages
                })
            return jsonify({"success": True, "message": f"成功删除 {success_count} 个用户"})
    else:
        print("未满足登录或管理员权限要求，无法批量删除用户")
        return jsonify({"success": False, "message": "请先登录或权限不足"})

# 创建数据库表结构的函数（如果表不存在则创建）
def create_database_tables():
    with sqlite3.connect(DB_PATH) as conn:
        cursor = conn.cursor()
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS competitions (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                name TEXT NOT NULL UNIQUE,
                deadline TEXT NOT NULL
            )
        ''')
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS competition_questions (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                competition_id INTEGER NOT NULL,
                question_order INTEGER NOT NULL,
                question_name TEXT NOT NULL,
                FOREIGN KEY (competition_id) REFERENCES competitions (id)
            )
        ''')
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS current_competition (
                id INTEGER PRIMARY KEY,
                competition_id INTEGER UNIQUE NOT NULL,
                FOREIGN KEY (competition_id) REFERENCES competitions (id)
            )
        ''')
        conn.commit()

@app.route('/getCurrentContestId', methods=['GET'])
def getCurrentContestId():
    try:
        with sqlite3.connect(DB_PATH) as conn:
            cursor = conn.cursor()
            # 先从current_competition表中获取当前比赛的ID
            cursor.execute('SELECT competition_id FROM current_competition')
            result = cursor.fetchone()
            if result:
                current_competition_id = result[0]
                # 根据获取到的当前比赛ID，从competitions表中查询该比赛的基础信息（id、name、deadline）
                cursor.execute('SELECT * FROM competitions WHERE id =?', (current_competition_id,))
                contest_info = cursor.fetchone()
                if contest_info:
                    # 将比赛基础信息整理成字典格式
                    contest_data = {
                        "id": contest_info[0],
                        "name": contest_info[1],
                        "deadline": contest_info[2],
                        "questions": []
                    }
                    # 关联查询该比赛下所有问题的顺序信息
                    print("check")
                    cursor.execute('''
                        SELECT question_order, question_name
                        FROM competition_questions
                        WHERE competition_id =?
                        ORDER BY question_order
                    ''', (current_competition_id,))
                    question_results = cursor.fetchall()
                    print(contest_data)
                    for question_result in question_results:
                        question_order = question_result[0]
                        question_name = question_result[1]
                        contest_data["questions"].append({
                            "question_order": question_order,
                            "question_name": question_name
                        })
                    return jsonify(contest_data)
                return jsonify({"message": "未找到对应比赛信息"}), 404
            return jsonify({"message": "未设置当前比赛"}), 404
    except Exception as e:
        print(f"查询当前比赛信息出现错误: {e}")
        return jsonify({"message": "查询当前比赛信息出现错误，请稍后再试"}), 500


@app.route('/api/activateContest', methods=['POST'])
def activateContest():
    try:
        contest_id = request.form.get('contest_id')  # 从前端POST请求的表单数据中获取比赛ID
        if not contest_id:
            return jsonify({"message": "缺少比赛ID参数"}), 400

        with sqlite3.connect(DB_PATH) as conn:
            cursor = conn.cursor()
            # 先查询current_competition表中是否已有记录
            cursor.execute('SELECT competition_id FROM current_competition')
            existing_record = cursor.fetchone()
            if existing_record:
                # 如果已有记录，直接更新为新传入的比赛ID
                cursor.execute('UPDATE current_competition SET competition_id =?', (contest_id,))
            else:
                # 如果没有记录，先插入一条初始记录（使用一个默认的初始值，这里假设为 -1，你可根据实际需求调整）
                cursor.execute('INSERT INTO current_competition (competition_id) VALUES (-1)')
                conn.commit()
                # 再更新为新传入的比赛ID
                cursor.execute('UPDATE current_competition SET competition_id =?', (contest_id,))
            conn.commit()
            return jsonify({"message": "激活比赛成功"})
    except Exception as e:
        print(f"激活比赛出现错误: {e}")
        return jsonify({"message": "激活比赛出现错误，请稍后再试"}), 500


# 新增创建比赛路由
@app.route('/create_competition', methods=['POST'])
def create_competition():
    if 'logged_in' in session and session['is_admin']:
        try:
            # 获取前端发送的 JSON 数据
            competition_data = request.get_json()
            competition_name = competition_data['competition_name']
            competition_deadline = competition_data['competition_deadline']
            questions = competition_data['questions']
            print("创建比赛题目：", questions)
            # 检查同名比赛
            with sqlite3.connect(DB_PATH) as conn:
                cursor = conn.cursor()
                cursor.execute('SELECT * FROM competitions WHERE name =?', (competition_name,))
                existing_competition = cursor.fetchone()
                if existing_competition:
                    return jsonify({"success": False, "message": "同名比赛已存在，创建失败"})

            # 将比赛信息存入数据库
            with sqlite3.connect(DB_PATH) as conn:
                cursor = conn.cursor()
                # 插入比赛基本信息到competitions表
                cursor.execute('INSERT INTO competitions (name, deadline) VALUES (?,?)',
                               (competition_name, competition_deadline))
                competition_id = cursor.lastrowid

                # 插入题目信息到competition_questions表，同时关联比赛
                for index, question_name in enumerate(questions, start=1):
                    cursor.execute('INSERT INTO competition_questions (competition_id, question_order, question_name) VALUES (?,?,?)',
                                   (competition_id, index, question_name))
                conn.commit()

            # 创建以比赛名称命名的文件夹
            folder_path = os.path.join('competition_files', competition_name)
            os.makedirs(folder_path, exist_ok=True)

            return jsonify({"success": True, "message": "比赛创建成功"})
        except Exception as e:
            print(f"创建比赛出现错误: {e}")
            return jsonify({"success": False, "message": "创建比赛出现错误，请稍后再试"})
    else:
        print("未满足登录或管理员权限要求，无法创建比赛")
        return jsonify({"success": False, "message": "请先登录或权限不足"})
        

# 获得比赛序列
@app.route('/get_contest_list', methods=['GET'])
def get_contest_list():
    if 'logged_in' in session and session['is_admin']:
        try:
            with sqlite3.connect(DB_PATH) as conn:
                cursor = conn.cursor()
                # 先查询competitions表获取所有比赛基本信息
                cursor.execute('SELECT id, name, deadline FROM competitions')
                contests = cursor.fetchall()
                contest_list = []
                for contest in contests:
                    contest_id = contest[0]
                    contest_info = {
                        "id": contest_id,
                        "name": contest[1],
                        "deadline": contest[2],
                        "questions": []
                    }
                    # 根据当前比赛的id，去competition_questions表中查询对应的题目信息
                    cursor.execute('''
                        SELECT question_name
                        FROM competition_questions
                        WHERE competition_id =?
                        ORDER BY question_order
                    ''', (contest_id,))
                    questions = [q[0] for q in cursor.fetchall()]
                    # print("检查 get_contest_list, contest name: ", questions)
                    contest_info["questions"] = questions
                    contest_list.append(contest_info)
                return jsonify({"success": True, "contestList": contest_list})
        except Exception as e:
            print(f"获取比赛列表出现错误: {e}")
            return jsonify({"success": False, "message": "获取比赛列表出现错误，请稍后再试"})
    else:
        print("未满足登录或管理员权限要求，无法获取比赛列表")
        return jsonify({"success": False, "message": "请先登录或权限不足"})


# 删除比赛
@app.route('/delete_contest', methods=['POST'])
def delete_contest():
    if 'logged_in' in session and session['is_admin']:
        try:
            # 判断前端传来的数据格式，这里先考虑表单数据格式（如果前端以JSON格式发送，需相应调整获取数据的方式）
            if request.form:
                print("批量")
                contest_ids = request.form.getlist('contest_ids')  # 批量删除时获取比赛ID列表
            elif request.get_json():
                print("单个")
                data = request.get_json()
                print(data)
                tmp = data.get('contest_id', [])  # 从JSON数据中获取比赛ID列表（若不存在则默认为空列表）
                contest_ids = []
                contest_ids.append(tmp)
                print("check: ", contest_ids)
            else:
                return jsonify({"success": False, "message": "未接收到有效的比赛ID数据"})

            print("比赛：", contest_ids)
            with sqlite3.connect(DB_PATH) as conn:
                cursor = conn.cursor()
                error_list = []
                for contest_id in contest_ids:
                    try:
                        # 先删除competition_questions表中与该比赛相关的关联记录（根据实际关联关系调整SQL语句）
                        cursor.execute('DELETE FROM competition_questions WHERE competition_id =?', (contest_id,))
                        # 再删除competitions表中的该比赛记录
                        cursor.execute('DELETE FROM competitions WHERE id =?', (contest_id,))
                        conn.commit()
                    except sqlite3.Error as e:
                        error_list.append(f"删除比赛（ID：{contest_id}）时出错，原因：{str(e)}")

                if error_list:
                    return jsonify({"success": False, "message": "部分比赛删除失败，详细错误信息如下：", "error_list": error_list})

            return jsonify({"success": True, "message": "比赛删除成功"})

        except Exception as e:
            print(f"删除比赛出现错误: {e}")
            return jsonify({"success": False, "message": "删除比赛出现错误，请稍后再试"})
    else:
        print("未满足登录或管理员权限要求，无法删除比赛")
        return jsonify({"success": False, "message": "请先登录或权限不足"})

# 下载比赛
@app.route('/download_contest_file', methods=['GET'])
def download_contest_file():
    contest_id = request.args.get('contest_id')
    if not contest_id:
        return jsonify({"success": False, "message": "缺少比赛ID参数"}), 400

    # 从数据库中根据比赛id查询比赛名称
    try:
        with sqlite3.connect(DB_PATH) as conn:
            cursor = conn.cursor()
            cursor.execute('SELECT name FROM competitions WHERE id =?', (contest_id,))
            result = cursor.fetchone()
            if not result:
                return jsonify({"success": False, "message": "未找到对应比赛信息"}), 404
            competition_name = result[0]
    except Exception as e:
        print(f"查询比赛名称出现错误: {e}")
        return jsonify({"success": False, "message": "查询比赛信息出现错误，请稍后再试"}), 500

    # 构建比赛文件夹的完整路径
    competition_folder_path = os.path.join(COMPETITION_FILES_ROOT, competition_name)
    if not os.path.exists(competition_folder_path):
        return jsonify({"success": False, "message": "比赛文件夹不存在"}), 404
    else:
        print("比赛目录存在：", competition_folder_path)

    # 创建临时的zip文件，放在一个临时目录下（例如可以是系统的临时文件夹，这里假设为/tmp，你可根据实际调整）
    import tempfile
    temp_dir = COMPETITION_FILES_ROOT
    # print("主目录：", temp_dir)
    zip_file_path = os.path.join(temp_dir, f"{competition_name}_files.zip")
    # print("打包为对象：", zip_file_path)

    try:
        # 使用with语句打开ZipFile，确保资源正确释放
        with ZipFile(zip_file_path, 'w') as zipf:
            # 遍历比赛文件夹及其子文件夹下的所有文件，将它们添加到zip文件中
            for root, dirs, files in os.walk(competition_folder_path):
                for file in files:
                    file_full_path = os.path.join(root, file)
                    arcname = os.path.relpath(file_full_path, competition_folder_path)
                    zipf.write(file_full_path, arcname=arcname)

        try:
            with open(zip_file_path, 'rb') as file:
                file_data = file.read()
            file_name = os.path.basename(zip_file_path)
            response = Response(
                file_data,
                content_type='application/zip',  # 根据文件类型设置正确的Content-Type
                headers={
                    'Content-Disposition': f'attachment; filename="{file_name}"'
                }
            )
            response.headers['X-Competition-Name'] = competition_name
            return response
        except Exception as e:
            print(f"发送zip文件出现错误: {e}")
            return jsonify({"success": False, "message": "文件下载出现错误，请稍后再试"}), 500
    except FileNotFoundError as fnfe:
        print(f"文件相关操作出现文件不存在错误: {fnfe}")
        return jsonify({"success": False, "message": "文件或文件夹不存在，无法进行打包或下载操作"}), 404
    except PermissionError as pe:
        print(f"文件相关操作出现权限错误: {pe}")
        return jsonify({"success": False, "message": "没有权限访问文件或文件夹，无法进行打包或下载操作"}), 403
    except Exception as e:
        print(f"发送zip文件出现错误: {e}")
        return jsonify({"success": False, "message": "文件下载出现错误，请稍后再试"}), 500
    finally:
        # 无论是否成功发送文件，都删除临时创建的zip文件（如果存在）
        #print("先不删除，确定后台没问题")
        #'''
        if os.path.exists(zip_file_path):
            try:
                os.remove(zip_file_path)
            except OSError as ose:
                print(f"删除临时zip文件出现错误: {ose}")
        #'''

# 上传文件
@app.route('/submit_answer', methods=['POST'])
def submit_answer():
    #print("上传的post: ", request.form.get('username'))
    username = request.form.get('username')
    questname = request.form.get('questionName')
    if 'file' not in request.files:
        return {"message": "没有接收到文件"}, 400
    file = request.files['file']
    if file.filename == '':
        return {"message": "文件名不能为空"}, 400

    # 确保文件名安全（去除一些可能有安全隐患的特殊字符等）
    filename = secure_filename(file.filename)

    # 连接数据库，获取当前比赛编号
    with sqlite3.connect(DB_PATH) as conn:
        cursor = conn.cursor()
        # 从current_competition表中查询当前比赛编号，假设该表只有一条记录对应当前比赛
        cursor.execute("SELECT competition_id FROM current_competition LIMIT 1")
        result = cursor.fetchone()
        
        if result is None:
            return {"message": "无法获取当前比赛编号"}, 400
        current_competition_id = result[0]

        # 根据当前比赛编号从competitions表中查询比赛名称
        cursor.execute("SELECT name FROM competitions WHERE id =?", (current_competition_id,))
        result = cursor.fetchone()
        
        if result is None:
            return {"message": "无法获取对应比赛名称"}, 400
        current_competition_name = result[0]

    print("cut_comname:", current_competition_name)
    # 构建比赛对应目录路径
    competition_dir = os.path.join(COMPETITION_FILES_ROOT, current_competition_name, username, questname)
    print("存储目录：", competition_dir)
    if not os.path.exists(competition_dir):
        os.makedirs(competition_dir)
    file_path = os.path.join(competition_dir, filename)

    try:
        file.save(file_path)
        return {"message": "文件上传成功"}
    except Exception as e:
        print(f"文件保存出现错误: {e}")
        return {"message": "文件保存出现错误，请稍后再试"}, 500



if __name__ == '__main__':
    create_database_tables()
    create_user_table()
    init_super_admin()
    app.run(debug=True)